﻿using System.Xml.Serialization;
using System.IO;

namespace MSDNWebcast.Utils
{
    public sealed class XmlSerializationHelper
    {
        #region Methods

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static T Deserialize<T>(Stream stream)
        {
            var serializer = new XmlSerializer(typeof(T));
            var result = (T)serializer.Deserialize(stream);
            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="reader"></param>
        /// <returns></returns>
        public static T Deserialize<T>(TextReader reader)
        {
            var serializer = new XmlSerializer(typeof(T));
            var result = (T)serializer.Deserialize(reader);
            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static T Deserialize<T>(string xml)
        {
            using (var reader = new StringReader(xml))
            {
                return Deserialize<T>(reader);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string Serialize<T>(object obj)
        {
            var serializer = new XmlSerializer(typeof(T));
            using (var writer = new StringWriter())
            {
                serializer.Serialize(writer, obj);
                return writer.ToString();
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="stream"></param>
        /// <param name="obj"></param>
        public static void Serialize<T>(Stream stream, object obj)
        {
            var serializer = new XmlSerializer(typeof(T));
            serializer.Serialize(stream, obj);
        }

        #endregion        
    }
}